import { getTranstionProp } from '../_tool/transition'
export default {
  name: 'CellAction',
  data() {
    return {
      moveX: 0,
      x1: 0,
      ismove: false,
      startX: 0, startY: 0,
      actionWidth: 0
    }
  },
  methods: {
    touchstart(e) {
      this.$refs.scroll.focus()
      if (this.$refs.actions && !this.actionWidth) {
        this.actionWidth = this.$refs.actions.offsetWidth
      }
      this.ismove = true
      let { pageX, pageY } = e.touches[0]
      this.startX = pageX
      this.startY = pageY
    },
    touchmove(e) {
      if (this.ismove) {
        let { pageX, pageY } = e.touches[0]
        let { startX, startY } = this
        if (Math.abs(pageX - startX) > Math.abs(pageY - startY) || Math.abs(this.x) > 0) {
          e.stopPropagation()
          e.preventDefault()
          let moveX = pageX - startX + this.x1
          this.moveX = moveX
          if (Math.abs(this.moveX) >= this.actionWidth) {
            this.$refs.actions.style.width = this.actionWidth + Math.abs(this.actionWidth + this.moveX) + 'px'
          }
        }
      }
    },
    touchend() {
      this.ismove = false;
      if (this.moveX >= 0) {
        this.moveX = this.x1 = 0
      } else {
        if (this.$refs.actions) {
          if (Math.abs(this.moveX + this.x1) >= (this.actionWidth / 2)) {
            this.moveX = -this.actionWidth
            this.x1 = this.moveX
          } else {
            this.x1 = this.moveX = 0
          }
          this.$refs.actions.style.width = this.actionWidth + 'px'
        }
      }
    },
    blur() {
      this.moveX = this.x1 = 0
    }
  },
  render() {
    let { $slots, moveX } = this
    let action = $slots.action
    let actionNode = action ? <div class="k-cell-actions" ref="actions" style={{ transition: this.ismove ? null : 'all .3s' }}>{$slots.action}</div> : null
    let props = {
      class: 'k-cell-action-inner',
      attrs: { tabIndex: 0 },
      ref: 'scroll',
      style: {
        transform: `translate(${moveX}px)`,
        transition: this.ismove ? null : 'all .3s'
      },
      on: {
        touchstart: e => this.touchstart(e),
        touchmove: e => this.touchmove(e),
        touchend: e => this.touchend(e),
        blur: this.blur
      }
    }
    let transform = getTranstionProp()
    return (
      <transition {...transform}>
        <div class="k-cell-action" ref="main">
          <div {...props} onTouchStart>
            <div class="k-cell-content">{$slots.content}</div>
            {actionNode}
          </div>
        </div>
      </transition>
    )
  }
}